<template>
  <div class="apps">
    <!--    <vc-loading ref="loading"/>-->
    <div class="law-content-wrapper">
      <!--      <div class="dirBtn" @click="openDir" v-if="dirArr">-->
      <!--        <img src="./dir.png"/>目录-->
      <!--      </div>-->
      <div class="leftDir" id="leftDir" v-if="dirArr?.length">
        <div class="directoryNav">
          <template v-for="(item, index) in dirArr" :key="item">
            <dt
              :class="{ selected: selectedId === item.id.trim() }"
              :id="item.id.trim()"
              @click="scrollToPosition(item.id.trim())"
            >
              {{ item.name }}
              <img
                src="./selected_yes.png"
                v-if="selectedId === item.id.trim()"
              />
            </dt>
            <dd
              :class="{ selected: selectedId === t.id }"
              v-for="(t, i) in item.values"
              :id="t.id.trim()"
              :key="index + '-' + i"
              @click="scrollToPosition(t.id)"
            >
              {{ t.name }}
              <img
                src="./selected_yes.png"
                v-if="selectedId === t.id"
              />
            </dd>
          </template>
        </div>
      </div>
      <div ref="lawHtml" class="html" id="html" v-html="html"/>
    </div>


    <!--    <no-data :type="200" v-if="!html"/>-->
  </div>
</template>
<script lang="ts" setup>
import { urlParse } from '@vc/utils';
import axios from 'axios';
import pako from 'pako';
import { decodeByBase64 } from '@vc/utils';
import { useNamespace } from 'vc/src/use';

const route = useRoute();
const paramsRoute = route.params;
let params = $ref<Record<string, any>>(JSON.parse(decodeURIComponent(decodeByBase64(paramsRoute.data as string))));
const _axios = axios.create({
  timeout: 60000, // 设置最大请求时间
  headers: {
    'Content-Type': 'application/json; charset=UTF-8'
  }
});

interface paramsProps {
  catalogueUrl: string
  hierarchicalCode: string
  lawName: string
  lawTitle: string
  lawUrl: string
}

let html = $ref('');
const lawHtml = ref<HTMLElement | null>();
let dirArr = ref<any[]>([]);
let show = $ref(false);
let isLoading = $ref(false);
let isNodata = $ref(false);
let loading = ref();
let selectedId = $ref('');
let paramsData = $ref<any>();

const openDir = () => {
  show = true;
  // 打开菜单栏时候，定位到当前章节的目录
  nextTick(() => {
    document.querySelector('.directoryNav')?.querySelectorAll('*').forEach((item) => {
      if (item.classList.contains('selected')) {
        item.scrollIntoView();
      }
    });
  });
};
const scrollToPosition = (id) => {
  show = false;
  selectedId = id;
  // 首先给之前高亮的章节恢复默认色
  document.querySelector('.html')?.querySelectorAll('*').forEach((item) => {
    (item as HTMLElement).style.backgroundColor = '#ffffff';
  });
  nextTick(() => {
    // @ts-ignore
    document.querySelector('[id=html]').querySelector('[id=\'' + id + '\']').style.display = 'block';
    // @ts-ignore
    document.querySelector('[id=html]').querySelector('[id=\'' + id + '\']').scrollIntoView();
    // @ts-ignore
    document.querySelector('[id=html]').querySelector('[id=\'' + id + '\']').style.backgroundColor = '#FAFAFA';
  });
};


// const pageScroll = () => {
//
// };
onMounted(() => {
  // loading.value.open();
  params = urlParse();
  if (params) {
    paramsData = JSON.parse(decodeURIComponent(decodeByBase64(paramsRoute.data as string)));
    let fileType = paramsData?.lawUrl.split('?')[0].split('.').pop().toLowerCase();
    let fileTypeCate = paramsData?.catalogueUrl
      .split('?')[0]
      .split('.')
      .pop()
      .toLowerCase();
    // 目录请求
    let actionDir: any = {
      method: 'get',
      url: paramsData.catalogueUrl,
      responseType: fileTypeCate === 'zlib' ? 'arraybuffer' : 'text'
    };
    // 正文请求
    let actionHtml: any = {
      method: 'get',
      url: paramsData.lawUrl,
      responseType: fileType === 'zlib' ? 'arraybuffer' : 'text'
    };
    // 请求目录数据
    _axios(actionDir).then((resc) => {
      if (resc.data) {
        // t.isLoading = false;
        if (fileTypeCate === 'zlib') {
          var words = new Uint8Array(resc.data),
            content = new TextDecoder('utf-8').decode(pako.inflate(words));
          dirArr.value = content && JSON.parse(content);
        } else {
          dirArr.value = resc.data;
        }
      }
    });
    // 请求正文数据
    _axios(actionHtml).then((res) => {
      if (res.data) {
        if (fileType === 'zlib') {
          var words = new Uint8Array(res.data),
            content = new TextDecoder('utf-8').decode(
              pako.inflate(words)
            );
          (html as any) = content.replaceAll('　', '');
        } else {
          (html as any) = res.data.replaceAll('　', '');
        }
        // 去除非utf-8的特殊字符
        (lawHtml.value as HTMLElement).innerHTML = html;
        // 滚动页面时候，获取当前章节的id
        nextTick(() => {
          const ele = (lawHtml.value as HTMLElement).getElementsByTagName('xuyan')[0];
          var div = document.createElement('div');
          div.innerText = '法律法规正文';
          div.className = 'hr line lawsZhengwen';
          // 法规上方信息，如果为null和空则显示'-'
          document.querySelector('.lawsInfo')?.querySelectorAll('.value')?.forEach((item) => {
            if ((item as HTMLElement).innerText === 'null' || (item as HTMLElement).innerText === '') {
              (item as HTMLElement).innerText = '-';
            }
          });
          if (ele) ele.appendChild(div);
          if (paramsData.hierarchicalCode) {
            nextTick(() => {
              scrollToPosition(paramsData.hierarchicalCode);
            });
          }
        });
      }
    }).finally(() => {
      // loading.value.close();
    });

    document.querySelector('.content-wrapper')?.addEventListener('scroll', function () {
      let arrDom = document.querySelector('.html')?.querySelectorAll('*') || [];
      let scrollTop = document.querySelector('.content-wrapper')?.scrollTop || 0;
      let scrollHeight = document.querySelector('.content-wrapper')?.scrollHeight || 0;
      let wHeight = (document.querySelector('.content-wrapper') as HTMLDivElement).offsetHeight;
      let offsetZhengwen = (document.querySelector('z0001') as HTMLElement)?.offsetTop || (document.querySelector('t0001') as HTMLElement)?.offsetTop || 600; // 正文的top值
      // 滚动到正文区域，标题显示法规名称，否则显示法规详情
      if (scrollTop > offsetZhengwen) {
        document.title = paramsData.lawTitle || paramsData.lawName;
      } else {
        document.title = '法规详情';
      }
      for (let i = 0; i < arrDom?.length; i++) {
        if (scrollTop >= ((arrDom[i] as HTMLElement).offsetTop - 71)) {
          let id = arrDom[i].id;
          if (id) {
            selectedId = id;
          }
        }
      }
      if (scrollHeight - scrollTop <= wHeight) {
        function getElementFc(j){
          const idNew = arrDom[arrDom.length - j].id;
          if (idNew) {
            if ((document.querySelector('[id=leftDir]') as HTMLDivElement).querySelector('[id=\'' + idNew + '\']')) {
              return idNew;
            } else {
              j++;
              return getElementFc(j);
            }
          } else {
            j++;
            return getElementFc(j);
          }
        }
        selectedId = (getElementFc(1) as any);
      }
    });
  }

});
</script>
<style scoped lang="scss">
.law-content-wrapper {
  background: #F5F5F5;
  display: flex;
  justify-content: center;
  box-sizing: border-box;
  min-height: 100%;

  .leftDir {
    width: 200px;
    background: #FFFFFF;
    border-radius: 4px;
    margin-left: 16px;
    padding: 16px;
    box-sizing: border-box;
    //margin-top: 16px;
    height: fit-content;
    margin-right: 16px;
    max-height: calc(100% - var(--vc-layout-header-height) - var(--vc-layout-footer-height));
    overflow-y: auto;
    position: fixed;
    left: calc((100% - 744px) / 2 - 236px);

    .directoryNav {
      padding: 10px 0;

      dt,
      dd {
        line-height: 42px;
        padding: 0px 15px;
        position: relative;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;

        img {
          width: 14px;
          position: absolute;
          right: 14px;
          top: 14px;
        }

        &.selected {
          background-color: #f5faff;
        }
      }

      dd {
        margin-left: 0;
        padding-left: 40px;
      }
    }
  }
}

.html {
  width: 744px;
  //margin-top: 16px;
  box-sizing: border-box;
  background: #fff;
  color: #111;
  padding: 24px 32px 500px 32px;
  min-height: 100%;
  font-size: 14px;
  line-height: 24px;
  overflow-x: hidden;
  max-width: 100%;
  white-space: pre-line;
}


:deep(.hr) {
  text-align: center;
  color: #d2d1d1;
  font-size: 13px;
  line-height: 18px;
  padding: 0 10px;
  margin: 27px 0 15px;
}

:deep(.hr::after) {
  content: "";
  height: 1px;
  width: calc(50% - 50px);
}

br {
  margin-bottom: 20px;
}


.hr {
  text-align: center;
  color: #d2d1d1;
  font-size: 13px;
  line-height: 18px;
  padding: 0 10px;
  margin-bottom: 15px;

  &::after {
    content: "";
    height: 1px;
    width: calc(50% - 50px);
  }

  &::before {
  }
}

.dirBtn {
  position: fixed;
  right: 8%;
  bottom: 17%;
  background: #64aaee;
  border-radius: 50%;
  font-size: 14px;
  color: #ffffff;
  width: 45px;
  height: 45px;
  text-align: center;

  img {
    display: block;
    padding: 7px 15px 3px 15px;
    width: 14px;
  }
}

.toTopBtn {
  position: fixed;
  right: 8%;
  bottom: 8%;

  width: 45px;
  height: 45px;
  background: #64aaee;
  border-radius: 50%;

  img {
    padding: 13px;
  }
}


:deep(.lawsInfo) {
  background: #f5faff !important;
  width: 100%;
  margin: 0 auto 8px;
  padding: 15px;
  box-sizing: border-box;
  white-space: initial;

  .row {
    display: flex;
    margin-bottom: 12px;
    background: #f5faff !important;

    &:last-child {
      margin-bottom: 0;
    }

    .item {
      flex: 1;
      display: flex;
      flex-shrink: 0;
      background: #f5faff !important;
    }

    .desc {
      flex-shrink: 0;
      font-style: normal;
      font-weight: 400;
      font-size: 13px;
      line-height: 18px;
      color: #8b8c8c;
      background: #f5faff !important;
    }

    .value {
      font-style: normal;
      font-weight: 400;
      font-size: 13px;
      line-height: 18px;
      background: #f5faff !important;
      color: #111111;
    }

    .label {
      display: flex;
      background: #2cd8c5 !important;
      border-radius: 2px;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      line-height: 18px;
      color: #ffffff;
      padding: 0 8px;
    }
  }
}
</style>
<style lang="scss">

.html > * {
  display: block;
}

xuyan .line {
  position: relative;
}

xuyan .line::before {
  content: "";
  width: 240px;
  height: 1px;
  background: #f6f6f6;
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
}

xuyan .line::after {
  content: "";
  width: 240px;
  height: 1px;
  background: #f6f6f6;
  position: absolute;
  right: 0;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

xuyanbiaoti {
  color: #8b8c8c;
  font-size: 12px;
  line-height: 20px;
  display: block;
  text-align: center;
  margin-bottom: -10px;
}

lawtitle {
  text-align: center;
  margin-bottom: 8px;
}

xuyan {
  margin-bottom: 27px;
}
lawtitle,xuyan {
  color: #8b8c8c;
  font-size: 12px;
  line-height: 20px;
  display: block;
}

biaoti {
  font-size: 18px;
  line-height: 25px;
  color: #111111;
  margin-bottom: 15px;
  font-weight: 600;
  display: block;
}

zhangtitle,
jietitle,
tiaotitle {
  font-size: 14px;
  line-height: 20px;
  color: #111;
  font-weight: bold;
  background: transparent !important;
}

lev1title,
lev2title,
lev3title  {
  font-weight: 600;
  margin-right: 6px;
  background: transparent !important;
}

</style>
